package com.guapi.event;

import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.guapi.dao.Event;
import com.guapi.service.ConversationService;
import com.guapi.service.UserService;
import com.guapi.util.KafkaConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 瓜皮哦
 */
@Component
public class EventConsumer implements KafkaConstant {
    private final static Log log = LogFactory.get();

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private UserService userService;

    @KafkaListener(topics = {"TEST"})
    public void handleTest(ConsumerRecord record) {
        log.warn("接收到Kafka信息");
        Event json = JSONUtil.toBean(JSONUtil.toJsonStr(record.value()), Event.class);
        System.out.println(json);
    }

    /**
     * 系统向用户发送消息通知
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_USER_REGISTER, TOPIC_EXPIRED_TASK, TOPIC_CANCEL_TASK, TOPIC_ACCEPT_TASK, TOPIC_FINISH_TASK})
    public void handlerSendMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("------------消息内容为空------------");
            return;
        }
        Event event = JSONUtil.toBean(JSONUtil.toJsonStr(record.value()), Event.class);
        if (event == null) {
            log.error("------------消息格式错误------------");
            return;
        }
        conversationService.sendConversation(event.getData(), 0, event.getUserId());
    }

    /**
     * 邮箱消息提醒
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_FINISH_TASK})
    public void handlerSendEmail(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("------------消息内容为空------------");
            return;
        }
        Event event = JSONUtil.toBean(JSONUtil.toJsonStr(record.value()), Event.class);
        if (event == null) {
            log.error("------------消息格式错误------------");
            return;
        }
        String userMail = userService.getUserMailById(event.getUserId());
        Map<String, Object> data = event.getData();
        //邮件应该发啥玩意？？？
        //下面发html还是发纯文本也可以从event设置，默认true吧
        MailUtil.send(userMail,
                // "在线接发单业务系统邮件通知服务，这里也能从event里拿出来",
                String.valueOf(data.get(DATA_KEY_TITLE)),
                // "此处是邮件文本，或许应该从event中拿出来",
                String.valueOf(data.get(DATA_KEY_CONTENT)),
                true);
    }
}
